<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <a-collapse-panel key="1" header="模板基本信息">
            <a-row :gutter="48">
              <a-col :span="8">
                <a-form-model-item label="模板编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateNo">
                  <a-input v-model="model.templateNo" placeholder="请输入模板编号" disabled ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="模板名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateName">
                  <a-input :disabled="formDisabled" v-model="model.templateName" placeholder="请输入模板名称" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="模板类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateType">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.templateType"
                   dictCode="template_type" placeholder="请选择模板类型" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经办人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <!-- <select-person-input
                :disabled=formDisabled
                @back="backUserInfo"
                v-model="model.proposer" /> -->
                  <select-user-by-dep placeholder="请选择经办人" :disabled="formDisabled" :multi="false" v-model="model.proposer" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经办部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart :disabled="formDisabled" v-model="model.proposerDeptId" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date :disabled="formDisabled" placeholder="请选择创建时间" v-model="model.createTime" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"/>
                </a-form-model-item>
              </a-col>
              <!--迭代6 task#1950业务分类修改-->
              <a-col :span="8">
                <a-form-item label="业务分类">
                  <a-tree-select
                    v-model="model.bussinessType"
                    :disabled="formDisabled"
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    placeholder="请选择业务分类"
                    allow-clear
                    tree-default-expand-all
                    :fieldNames="{ children: 'children', label: 'title', value: 'value' }"
                    :treeData="categoryTree"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="允许添加子节点" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isAddChildNode">
                  <j-dict-select-tag
                    type="radio"
                    v-model="model.isAddChildNode"
                    :disabled="formDisabled"
                    dictCode="yes_no"
                    placeholder="请选择允许添加子节点"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="model.templateType != '2'">
                <a-form-model-item label="收入确认方式" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="confirmIncomeMethod">
                  <j-dict-select-tag
                    :disabled="formDisabled"
                    type="list"
                    v-model="model.confirmIncomeMethod"
                    dictCode="confirm_income_method"
                    placeholder="请选择收入确认方式"
                    @input="handleConfirmIncomeMethod" />
                </a-form-model-item>
              </a-col>
              <!--迭代6 task#1950业务分类修改end-->
              <a-col :span="24">
                <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
                  <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!--          业务分类-->
          <a-collapse-panel key="2" header="进度节点信息">
            <a-row>
              <a-col :span="24">
                <div style="margin-bottom: 6px;margin-top: 6px">
                  <a-button @click="handleAdd" v-if="!formDisabled" type="primary">新增</a-button>
                  <a-popconfirm
                    v-if="!formDisabled && selectedRowKeys.length"
                    style="margin-left: 20px;"
                    placement="top"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="handleDeletes">
                    <template slot="title">
                      <p>是否删除选中的列表？</p>
                    </template>
                    <a-button type="primary">删除</a-button>
                  </a-popconfirm>
                </div>
                <a-table
                  ref="table"
                  size="middle"
                  rowKey="dataId"
                  :customRow="customRow"
                  :loading="loading"
                  :columns="columns"
                  :scroll="{y: tableHeight}"
                  :pagination="false"
                  :row-selection="!formDisabled? { selectedRowKeys: selectedRowKeys, onChange: onSelectChange } : null"
                  :data-source="dataSource">
                  <span slot="action" slot-scope="text, record, index">
                    <template v-if="!formDisabled">
                      <a-popover trigger="hover">
                        <template slot="content">
                          <p @click="handlerUp(text, record, index)" class="hover">上移</p>
                          <p @click="handlerDown(text, record, index)" class="hover">下移</p>
                          <p @click="addOne(text, record, index)" class="hover">插入一行</p>
                        </template>
                        <a-button icon="unordered-list" type="primary" :ghost="true" class="ruleButton">
                          <!-- <a-icon type="unordered-list" /> -->
                        </a-button>
                      </a-popover>
                      <a-divider type="vertical"/>
                      <a-button
                        class="ruleButton"
                        :ghost="true"
                        type="primary"
                        icon="edit"
                        @click="handleEdit(record, index)"/>
                      <a-divider type="vertical"/>
                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(index)">
                        <a-button
                          class="ruleButton"
                          :ghost="true"
                          type="primary"
                          icon="delete"
                        />
                      </a-popconfirm>
                    </template>
                  </span>
                  <template slot="titleSlot" slot-scope="text">
                    <span v-if="text">
                      {{ text }}%
                    </span>
                    <span v-if="!text">
                      -
                    </span>
                  </template>
                </a-table>
              </a-col>
              <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
                <a-button @click="submitForm">提 交</a-button>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
        <erp-progress-template-dt-modal ref="itemList" @ok="modalFormOk" :insertRows="insertRows" :confirmIncomeMethod="model.confirmIncomeMethod"></erp-progress-template-dt-modal>

      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
import { filterObj } from '@/utils/util'
import SelectPersonInput from '@/views/scy/components/SelectPersonInput'
import ErpProgressTemplateDtModal from './ErpProgressTemplateDtModal.vue'
import { mapGetters } from 'vuex';
import moment from 'moment';
import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
import { filterMultiDictText, initDictOptions } from '@comp/dict/JDictSelectUtil';

export default {
    name: 'ErpProgressTemplateForm',
    components: {
      SelectPersonInput,
      ErpProgressTemplateDtModal,
      SelectUserByDep
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        /* 排序参数 */
        insertRows: null, // 插入的行
        selectedRowKeys: [], // 选中的列表
        isorter: {
          column: 'sortOrder',
          order: 'desc'
        },
        activeKey: ['1', '2'],
        model: {},
        loading: false,
        labelCol: {
        },
        columns: [
          {
            title: '节点名称',
            align: 'center',
            dataIndex: 'nodeName'
          },
          {
            title: '节点进度',
            align: 'center',
            dataIndex: 'nodeProgress',
            scopedSlots: { customRender: 'titleSlot' }
          },
          {
            title: '证明材料是否必填',
            align: 'center',
            dataIndex: 'isValidateRequired',
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['YES_OR_NO'], text + '')
              }
            }
          },
          {
            title: '收入确认节点',
            align: 'center',
            dataIndex: 'isConfirmIncomeNode',
            customRender: (text) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['YES_OR_NO'], text + '')
              }
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: {
              filterDropdown: 'filterDropdown',
              filterIcon: 'filterIcon',
              customRender: 'action'
            }
          }
        ],
        dataSource: [],
        tableHeight: 0,
        // 分类
        categoryTree: [],
        dictOptions: {},
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          templateName: [
            { required: true, message: '请输入模板名称!', whitespace: true }
          ],
          templateType: [
            { required: true, message: '请输入模板类型!', whitespace: true }
          ],
          isAddChildNode: [
            { required: true, message: '请选择允许添加子节点!', whitespace: true }
          ],
          confirmIncomeMethod: [
            { required: true, message: '请选择收入确认方式!', whitespace: true }
          ]
        },
        url: {
          addOrEdit: '/api/erp/progress/erpProgressTemplate/addOrEdit',
          edit: '/api/erp/progress/erpProgressTemplate/addOrEdit',
          queryById: '/api/erp/progress/erpProgressTemplate/queryById',
          erpProgressTemplateDtList: '/api/erp/progress/erpProgressTemplateDt/list',
          generatedFormNumber: '/api/erp/base/generatedFormNumber',
          categoryTree: '/api/erp/files/category/filesBusinessCategory/queryTreeList'
        },

        sourceIndex: null,
        targetIndex: null

      }
    },
    computed: {

      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      // 加载分类
      this.initcategoryTree();
      // 加载数据字典
      // 加载数据字典信息
      this.initDictConfig();
    },
    mounted () {
      var that = this
      that.tableHeight = document.body.clientHeight - 370;
    },
    methods: {
      handleConfirmIncomeMethod (val) {
        this.dataSource.map(item => {
          item.isConfirmIncomeNode = '0'
        })
        console.log('this.dataSource', this.dataSource)
      },
      initDictConfig() {
        initDictOptions('YES_OR_NO').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'YES_OR_NO', res.result)
          }
        })
      },
      // 拖动排序
      customRow(record, index) {
        return {
          style: {
            cursor: 'move'
          },
          on: {
            // 鼠标移入
            mouseenter: (event) => {
              // 兼容IE
              var ev = event || window.event;
              ev.target.draggable = true;
            },
            // 开始拖拽
            dragstart: (event) => {
              // 兼容IE
              var ev = event || window.event;
              // 阻止冒泡
              ev.stopPropagation();
              // 得到源目标数据
              this.sourceIndex = index;
            },
            // 拖动元素经过的元素
            dragover: (event) => {
              // 兼容 IE
              var ev = event || window.event;
              // 阻止默认行为
              ev.preventDefault();
            },
            // 鼠标松开
            drop: (event) => {
              // 兼容IE
              var ev = event || window.event;
              // 阻止冒泡
              ev.stopPropagation();
              // 得到目标数据
              this.targetIndex = index;
              this.reorder(this.sourceIndex, this.targetIndex)
            }
          }
        };
      },

      // 拖动后的排序
      reorder (start, end) {
        if (start !== null && end !== null) {
          let temp = this.dataSource[start]
          this.dataSource.splice(start, 1)
          this.dataSource.splice(end, 0, temp)
        }
      },
      generatedFormNumber() {
        getAction(this.url.generatedFormNumber, { prefix: 'ERPJDMB', subSystemCode: '05' }).then(res => {
          if (res.success) {
            // this.model.templateNo = res.result
            this.$set(this.model, 'templateNo', res.result);
          }
        })
      },

      // 选中的列表
      onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
      },

      // 点击批量删除
      handleDeletes () {
        this.loading = true;
        this.dataSource = this.dataSource.filter((item) => !this.selectedRowKeys.some(item2 => item2 == item.dataId))
        this.selectedRowKeys = []
        this.loading = false
      },

      handleAdd () {
        if(this.model.templateType != '2' && !this.model.confirmIncomeMethod){
          this.$message.warning('请先选择收入确认方式！')
          return false
        }
        this.$refs.itemList.add();
        this.$refs.itemList.title = '模板创建';
        this.$refs.itemList.disableSubmit = false;
        this.insertRows = null
      },
      handleEdit(record, index) {
        this.$refs.itemList.edit(record, index);
        this.insertRows = null
        this.$refs.itemList.title = '模板编辑';
        this.$refs.itemList.disableSubmit = false;
      },
      handleDelete(index) {
        this.dataSource.splice(index, 1);
      },
      modalFormOk(data, index) {
        this.loading = true;
        // 当插入行
        if (this.insertRows !== null) {
          this.dataSource.splice(this.insertRows, 0, data);
        } else {
          // 没有插入行
          if (index !== -1) {
          this.dataSource.splice(index, 1, data);
        } else {
          this.dataSource.push(data);
        }
        }
        this.loading = false;
      },
      ...mapGetters(['userInfo']),
      add (value) {
        this.dataSource = []
        this.edit(this.modelDefault);
        this.model.proposer = this.userInfo().empId;
        // this.model.handlerName=value.loginUser.realname;
        // this.model.proposerDeptId = this.userInfo().deptId;
        this.$set(this.model, 'proposerDeptId', this.userInfo().deptId)
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        if (this.model.id) {
          let param = {
            mainId: this.model.id,
            pageSize: 10000,
            column: 'sortOrder',
            order: 'asc'
          }
          getAction(this.url.erpProgressTemplateDtList, param).then((res) => {
            if (res.success) {
              this.dataSource = res.result.records || res.result
              this.dataSource.map(value => {
                value.dataId = value.id
                return value
              })
            }
          })
        } else {
          this.generatedFormNumber();
        }
        this.visible = true;
      },

      // 点击上移
      handlerUp (text, record, index) {
        if (index == 0) {
          this.$message.warning('已在第一列了！')
          return false
        }
        let temp = this.dataSource[index - 1];
        this.$set(this.dataSource, index - 1, this.dataSource[index])
        this.$set(this.dataSource, index, temp)
      },
      // 点击下移
      handlerDown (text, record, index) {
        if (index == this.dataSource.length - 1) {
          this.$message.warning('已在最后一列了！')
          return false
        }
        let temp = this.dataSource[index + 1];
        this.$set(this.dataSource, index + 1, this.dataSource[index])
        this.$set(this.dataSource, index, temp)
      },

      // 点击插入一行
      addOne (text, record, index) {
        this.insertRows = index
        this.$refs.itemList.add();
        this.$refs.itemList.title = '节点新增';
        this.$refs.itemList.disableSubmit = false;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },
      getQueryParams() {
        let param = Object.assign({}, {}, this.isorter);
        return filterObj(param);
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.confirmLoading = true;
            let httpurl = this.url.addOrEdit;
            let method = 'post';
            if (this.dataSource.length === 0) {
              that.$message.warning('请输入模板节点明细信息');
              that.confirmLoading = false
              return
            }
            // 模板明细新增清空id
            // if (!this.model.id) {
            //   Object.keys(this.dataSource).forEach(key => (this.dataSource[key].id = ''));
            // }
            this.model.erpProgressTemplateDtList = this.dataSource;
            httpAction(httpurl, this.model, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message);
                that.$emit('ok');
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
      // 初始化分类树
      initcategoryTree() {
          getAction(this.url.categoryTree).then(res => {
            if (res.success) {
              this.categoryTree = res.result
            }
          })
      },
      backUserInfo(data) {
        this.$set(this.model, 'proposerDeptId', data[0].departmentId)
      }
    }
  }
</script>
<style scoped="scoped">
.hover{
  cursor: pointer;
}
.hover:hover{
  color: #1890ff;
}
</style>
